﻿using System.Data;
using System.Data.SqlClient;

namespace QuanLyTuyenSinh.DataLayer
{
    public class DataConfig
    {
        private readonly SqlConnection _sqlConnection;
        private DataTable _dtTable;
        private SqlDataAdapter _sqlAdapter;
        private SqlCommand _sqlCommand;

        public DataConfig(string serverName, string userName, string pass)
        {
            string connectionString = string.Format("Data Source={0};Initial Catalog=TuyenSinh;User ID={1};Password={2}", serverName, userName, pass);
            _sqlConnection = new SqlConnection(connectionString);
            _sqlConnection.Open();

            if (_sqlConnection.State == ConnectionState.Open)
                _sqlConnection.Close();
        }

        public DataTable GetDataTable(string strCode)
        {
            _dtTable = new DataTable();
            _sqlAdapter = new SqlDataAdapter(strCode, _sqlConnection);
            _sqlAdapter.Fill(_dtTable);
            return _dtTable;
        }

        public int ExecuteNoneQuery(string strCode)
        {
            int ressult = 0;
            if (_sqlConnection.State == ConnectionState.Closed)
                _sqlConnection.Open();
            _sqlCommand = new SqlCommand(strCode, _sqlConnection);
            _sqlCommand.CommandType = CommandType.Text;
            ressult = _sqlCommand.ExecuteNonQuery();
            if (_sqlConnection.State == ConnectionState.Open)
                _sqlConnection.Close();
            return ressult;
        }

        public string ExecuteScalarQuery(string strCode)
        {
            string result = "";

            if (_sqlConnection.State == ConnectionState.Closed)
                _sqlConnection.Open();
            _sqlCommand = new SqlCommand(strCode, _sqlConnection);
            _sqlCommand.CommandType = CommandType.Text;
            result = _sqlCommand.ExecuteScalar().ToString();
            if (_sqlConnection.State == ConnectionState.Open)
                _sqlConnection.Close();
            return result;
        }
    }
}